/*
 * @lc app=leetcode.cn id=39 lang=cpp
 *
 * [39] 组合总和
 */
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cmath>
#include <numeric>

using namespace std;
// @lc code=start
class Solution {
public:
    vector<int> tmp;
    vector<vector<int>> ret;
    void dfs(int pos,vector<int>& candidates, int target,int sum) {
        if(sum > target) {
            return ;
        }
        if(sum == target) {
            ret.push_back(tmp);
            return ;
        }
        for(int i = pos;i < candidates.size();i++) {
            tmp.push_back(candidates[i]);
            sum += candidates[i];
            //确保本层使用后还能使用
            dfs(i,candidates,target,sum);
            sum -= candidates[i];
            tmp.pop_back();
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        dfs(0,candidates,target,0);
        return ret;
    }
};
// @lc code=end

